package org.example;

import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

public class Main {
    public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
        Configuration config = new Configuration();
        Job job = Job.getInstance(config);
        job.setJarByClass(Main.class);
        job.setJobName("数据清洗");

        job.setMapperClass(MyMapper.class);

        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(NullWritable.class);

        FileInputFormat.addInputPath(job, new Path(args[0]));
        Path outpath = new Path(args[1]);

        FileSystem fs = FileSystem.get(config);
        if (fs.exists(outpath)) {
            fs.delete(outpath, true);
        }

        FileOutputFormat.setOutputPath(job, outpath);
        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }


    public static class MyMapper extends Mapper<LongWritable, Text, Text, NullWritable> {
        private static final String SEP = "\u0001";

        @Override
        protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, NullWritable>.Context context) throws IOException, InterruptedException {
            String[] arr = value.toString().replace("\"", "").split(SEP);
            if ("id".equals(arr[0])) return;
            StringBuilder builder = new StringBuilder();
            for (String row : arr) {
                row = row.replaceAll("\\s+", " ").trim();
                row = StringUtils.isBlank(row) ? "" : row;
                try {
                    Double.parseDouble(row);
                    try {
                        Integer.parseInt(row);
                    } catch (NumberFormatException e) {
                        if (row.endsWith(".0")) {
                            row = row.replace(".0", "");
                        }
                    }
                } catch (NumberFormatException ignored) {
                }
                if (builder.length() == 0) builder.append(row);
                else builder.append(SEP).append(row);
            }
            context.write(new Text(builder.toString()), NullWritable.get());
        }
    }


}
